package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyt.message.Message;
import com.jyt.message.MessageConfig;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.GloableParams;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.adapter.NewFriendsAdapter;
import wetalk.software.bupt.com.wetalk.application.MyApplication;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClient;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.model.po.Applicant;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;

/**
 * 好友申请列表的界面
 */
public class NewFriendsActivity extends BaseActivity {
    private static final String TAG="NewFriendsActivity";
    private List<Applicant> list=new ArrayList<>();
    NewFriendsAdapter adapter;
    private AcceptAddReceiver receiver;
    private int mPosition;

    private AndroidClientService.SendBinder sendBinder;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_friends);
        initTitle();
        initReceiver();

        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);

        //点击textview跳入搜索用户的界面
        TextView tv=(TextView)findViewById(R.id.tv_friends_search);
        tv.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(NewFriendsActivity.this,AddFriendsActivity.class);
                startActivity(intent);
            }
        });
    }
    private void initReceiver(){
        IntentFilter intentFilter=new IntentFilter("addFriRes");
        receiver=new AcceptAddReceiver();
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onStart() {
        super.onStart();

        list= WeTalkDB.create(this).queryApplicantList();
        adapter=new NewFriendsAdapter(NewFriendsActivity.this,list);
        adapter.setOnAcceptListener(new NewFriendsAdapter.OnAcceptListener() {
            @Override
            public void onAccept(int position) {
                CustomDialog.getDialog(NewFriendsActivity.this,"正在添加...").show();
                Applicant apt=list.get(position);
                mPosition=position;
                sendAccept(apt.getId());
            }
        });
        ListView listView=(ListView)findViewById(R.id.lv_new_friend);
        listView.setAdapter(adapter);

    }

    private void sendAccept(String id){
        final String userId= UserManager.getInstance(NewFriendsActivity.this).getCurrentUser().getUserID();
        final String targetId = "sys_friend";
        final JSONObject json=new JSONObject();
        try {
            json.put("id",id);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"addFriRes",bs);

                sendBinder.sendMessage(msg);
            }
        });
        thread.start();
    }

    private void initTitle(){
        RelativeLayout rvRight=(RelativeLayout)findViewById(R.id.rv_img_right);
        rvRight.setVisibility(View.GONE);
        TextView txt=(TextView)findViewById(R.id.txt_title);
        txt.setText("新的朋友");
        RelativeLayout rvLeft=(RelativeLayout)findViewById(R.id.rv_img_back);
        rvLeft.setVisibility(View.VISIBLE);
        rvLeft.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        unregisterReceiver(receiver);
    }

    class AcceptAddReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            CustomDialog.getDialog(context,"正在添加...").close();
            SharedPreferences.Editor editor= context.getSharedPreferences("data",Context.MODE_PRIVATE).edit();
            String content=intent.getStringExtra("content");
            User user=new Gson().fromJson(content,User.class);
            if(user.getUserName()!=null){
                User u=WeTalkDB.create(context).queryFri(user.getUserID());
                if(u==null){
                    WeTalkDB.create(context).addFri(user);
                    Applicant apt=list.get(mPosition);
                    WeTalkDB.create(context).updateApplicant(apt.getId());
                }
                editor.putString("isAdd","yes");
                editor.apply();
            }
            abortBroadcast();
            finish();
        }
    }
}
